package com.iwish.server.model;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import com.google.code.morphia.Datastore;
import com.iwish.server.storage.DAO.MongoDAO;
import com.iwish.server.storage.DAO.SQLCommand;
import com.iwish.server.storage.model.Obj;
import com.iwish.server.util.Base64Util;
import com.iwish.server.util.RequestCode;
import com.iwish.server.util.Separator;

public class LoginService extends ServiceTemplate{
	
	Logger logger = Logger.getLogger(LoginService.class);

//	private static final String dbAddress = "192.168.1.103";
//	private static final int dbPort = 27017;
//	private static final int redisPort = 6379;
//
//	private static final String dbName = "MyDB";
//	private static final String collName = "user";

	private String username;
	private String password;
	private String uid;
	
//	public LoginService(User u , String cookie)
//	{
//		String username = u.getUsername();
//		String password = u.getPassword();
//		String uid = u.getUid();
//		
//		this.username = username;
//		this.password = password;
//		this.uid = uid;
//	}
//
//	public LoginService(String username, String password, String uid) {
//		this.username = username;
//		this.password = password;
//		this.uid = uid;
//	}
//	
	public LoginService(String uName, String password)
	{
		this.username = uName;
		this.password = password;
	}

	public boolean login(IoSession session) {
//		if(username == null || password== null || uid == null
//				|| username.length() <= 0 || password.length() <= 0
//				|| uid.length() <= 0)
//		{
//			System.out.println("login info invalid");
//			return false;
//		}
//		String pswFromDb;
//
//		// pswFromDb = getPasswordFromMongoDB();
//		pswFromDb = getPasswordFromRedis();
//		if (pswFromDb == null || pswFromDb.length() <= 0
//				|| !pswFromDb.equals(password)) {
//			return false;
//		}
//		return true;
		String uid = "u." + username;
		
		
		Object u = MongoDAO.execute(Obj.User.class, new SQLCommand() {
			
			@Override
			public Object sql(Class c, Datastore ds) {
				// TODO Auto-generated method stub
				return ds.find(c,"uname_",username).get();
				
			}
			
			@Override
			public void print() {
				// TODO Auto-generated method stub
				logger.debug("LoginService - get user from DB");
				
			}
		});
		
		//Object u = get(uid, Obj.User.class, 30);
		logger.debug("get username = " + ((Obj.User)u).getUname());
		if(!(u instanceof Obj.User))
		{
			logger.info("login failed");
			//TODO: turn String to StringBuilder
			String result = Base64Util.encode(RequestCode.LOGIN_RESULT.getBytes())
					+ Separator.F_SEPARATOR
					+ Base64Util.encode(RequestCode.FAIL.getBytes())
					+ Separator.F_SEPARATOR
					+ "No Such User"
					+ Separator.F_SEPARATOR
					+ Separator.F_SEPARATOR ;// empty user[]
			logger.info(result);
			session.write(result);
			return false;
		}
		Obj.User user = (Obj.User)u;
		
		if(null == user.getPwd()|| !(password.equals(user.getPwd())))
		{
			logger.info("login failed, password unvalid");
			logger.debug("password from db = " + user.getPwd());
			logger.debug("password from client = " + password);
			String result = Base64Util.encode(RequestCode.LOGIN_RESULT.getBytes())
					+ Separator.F_SEPARATOR
					+ Base64Util.encode(RequestCode.FAIL.getBytes())
					+ Separator.F_SEPARATOR
					+ "Password Invalid"
					+ Separator.F_SEPARATOR
					+ Separator.F_SEPARATOR ;// empty user[]
			logger.info(result);
			session.write(result);
			return false;
		}
		
		//wirte result back to client
		String gender = "0";
		if(user.getGender())
			gender = "1";
		
		String result = Base64Util.encode(RequestCode.LOGIN_RESULT.getBytes())
				+ Separator.F_SEPARATOR
				+ Base64Util.encode(RequestCode.SUCCESS.getBytes())
				+ Separator.F_SEPARATOR
				+ Separator.F_SEPARATOR // empty reason
				// user[] : uid,uname,nickname,gender,image
				+ Base64Util.encode(user.getUid().getBytes())
				+ Separator.S_SEPARATOR
				+ Base64Util.encode(user.getUname().getBytes())
				+ Separator.S_SEPARATOR
				+ Base64Util.encode(user.getNick().getBytes())
				+ Separator.S_SEPARATOR
				+ Base64Util.encode(gender.getBytes())
				+ Separator.S_SEPARATOR
				//+ Base64Util.encode(user.getImage())
				+ Separator.F_SEPARATOR;
		session.write(result);
		
		return true;
	}
	


//	private String getPasswordFromMongoDB() throws UnknownHostException {
//		Mongo m = new Mongo(dbAddress, dbPort);
//		DB db = m.getDB(dbName);
//		DBCollection coll = db.getCollection(collName);
//		DBObject doc = new BasicDBObject();
//		doc.put("username", username);
//		DBCursor cursor = coll.find(doc);
//
//		while (cursor.hasNext()) {
//			return (String) cursor.next().get("password");
//		}
//		return null;
//	}

//	private String getPasswordFromRedis() {
//		JRedis jr = new JRedisClient(dbAddress, redisPort);
//		try {
//			jr.ping();
//			User u = (User) SerializableUtil.unserialize(jr.mget("userOne")
//					.get(0));
//			return u.getPassword();
//		} catch (RedisException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			jr.quit();
//			return null;
//		}
//	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

}
